package iamutkarshtiwari.github.io.ananas.editimage.fragment;


import iamutkarshtiwari.github.io.ananas.ResourceTable;
import iamutkarshtiwari.github.io.ananas.editimage.EditImageAbility;
import iamutkarshtiwari.github.io.ananas.editimage.adapter.StickerAdapter;
import iamutkarshtiwari.github.io.ananas.editimage.adapter.StickerTypeAdapter;
import iamutkarshtiwari.github.io.ananas.editimage.utils.Matrix3;
import iamutkarshtiwari.github.io.ananas.editimage.utils.MyToast;
import iamutkarshtiwari.github.io.ananas.editimage.utils.PxUtil;
import iamutkarshtiwari.github.io.ananas.editimage.view.StickerItem;
import iamutkarshtiwari.github.io.ananas.editimage.view.StickerView;
import io.reactivex.Single;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.*;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.PixelMapHolder;
import ohos.agp.render.Texture;
import ohos.agp.utils.Matrix;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;

import java.util.LinkedHashMap;

public class StickerFragment extends ComponentContainer {
    private Context mContext;
    private PageSlider pageSlider;
    private Image back, contentBack;
    private EditImageAbility editImageAbility;
    private StickerView stickerView;
    private PageFlipper pageFlipper;
    private ListContainer typeList, contentList;
    private StickerTypeAdapter stickerTypeAdapter;
//    private int currentType = 0;
    private StickerAdapter stickerAdapter;
    private PixelMap addPixelMap;
    private CompositeDisposable compositeDisposable = new CompositeDisposable();
    EventHandler eventHandler = new EventHandler(EventRunner.getMainEventRunner());
    //记录是否需要回退
    private boolean backFlag = false;

    public StickerFragment(Context context, PageSlider pageSlider) {
        super(context);
        this.mContext = context;
        this.pageSlider = pageSlider;
        this.editImageAbility = (EditImageAbility) context;
        this.stickerView = editImageAbility.stickerView;
        initView();
    }

    public StickerFragment(Context context, AttrSet attrSet) {
        super(context, attrSet);
    }

    public StickerFragment(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
    }

    /**
     * Sticker界面的初始化
     */
    private void initView() {
        Component component = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_fragment_sticker_layout, null, false);
        addComponent(component);
        back = (Image) component.findComponentById(ResourceTable.Id_back_to_main);  //返回选择编辑功能的界面
//      stickerView.updateImageBitmap(abilitySlice.mainImage.getPixelMap());
//        stickerView.setBasePixel(abilitySlice.mainImage.getPixelMap());
        contentBack = (Image) component.findComponentById(ResourceTable.Id_back_to_type);
        pageFlipper = (PageFlipper) component.findComponentById(ResourceTable.Id_flipper);
        float height = PxUtil.vp2px(100);
        pageFlipper.setFlipPeriod(1000);
        pageFlipper.setOutgoingAnimation(new AnimatorProperty().setDuration(300).moveFromY(0).moveToY(-height));
        pageFlipper.setIncomingAnimation(new AnimatorProperty().setDuration(300).moveFromY(height).moveToY(0));

        typeList = (ListContainer) component.findComponentById(ResourceTable.Id_stickers_type_list);
        contentList = (ListContainer) component.findComponentById(ResourceTable.Id_stickers_list);
        typeList.setOrientation(Component.HORIZONTAL);  //设置横向显示
        contentList.setOrientation(Component.HORIZONTAL);
        stickerTypeAdapter = new StickerTypeAdapter(mContext);
        typeList.setItemProvider(stickerTypeAdapter);
        typeList.setItemClickedListener((listContainer, component12, i, l) -> {
            pageFlipper.showNext();
//            currentType = i;
            stickerAdapter = new StickerAdapter(mContext, i);
            contentList.setItemProvider(stickerAdapter);
            contentList.setVisibility(HIDE);
            eventHandler.postTask(() -> contentList.setVisibility(VISIBLE), 170);
            backFlag = true;
        });

        contentList.setItemClickedListener((listContainer, component1, i, l) -> {
            addPixelMap = stickerAdapter.getShowIcon().get(i);
            eventHandler.postTask(() -> stickerView.addBitImage(addPixelMap), 170);
        });

        back.setClickedListener(new ClickedListener() {
            @Override
            public void onClick(Component component) {
                backToMainLocal();
            }
        });

        contentBack.setClickedListener(new ClickedListener() {
            @Override
            public void onClick(Component component) {
                backFlag = false;
                pageFlipper.showPrevious();
                typeList.setVisibility(HIDE);
                eventHandler.postTask(() -> typeList.setVisibility(VISIBLE), 170);
            }
        });
    }

    /**
     * 切换到Sticker界面，显示需要的控件
     */
    public void onShow() {   //在mainView上绘制
        editImageAbility.mode = EditImageAbility.MODE_STICKERS;
        editImageAbility.stickerView.setVisibility(VISIBLE);
        backFlag = false;
        //不会移动到顶部，
        //typeList.scrollTo(0);
        //每次重新赋值 重新刷新
        stickerTypeAdapter = new StickerTypeAdapter(mContext);
        typeList.setItemProvider(stickerTypeAdapter);
    }

    /**
     * 返回主界面
     */
    public void backToMainLocal() {
        editImageAbility.mode = EditImageAbility.MODE_NONE;
        stickerView.clear();
        pageSlider.setCurrentPage(0, false);
        pageSlider.setVisibility(Component.HIDE);
        stickerView.setVisibility(HIDE);
        editImageAbility.saveOrApply(false);
    }

    /**
     * 返回主界面
     */
    public void backToMain() {
        editImageAbility.mode = EditImageAbility.MODE_NONE;
        stickerView.clear();
        pageSlider.setCurrentPage(0, false);
        pageSlider.setVisibility(Component.HIDE);
        stickerView.setVisibility(HIDE);
        editImageAbility.saveOrApply(false);
        if (backFlag) {
            pageFlipper.showPrevious();
        }
    }

    /**
     * Sticker修改后的效果应用
     */
    public void applyStickers() {

        compositeDisposable.clear();

        Disposable saveStickerDisposable = applyStickerToImage(editImageAbility.getMainBit())
//                .subscribeOn(Schedulers.computation())
//                .observeOn(Schedulers.mainThread())
//                .doOnSubscribe(subscriber -> loadingDialog.show())
//                .doFinally(() -> loadingDialog.dismiss())
                .subscribe(bitmap -> {
                    if (bitmap == null) {
                        return;
                    }

                    stickerView.clear();
                    editImageAbility.changeMainBitmap(bitmap, true);
                    backToMain();
                }, e -> {
                    MyToast.show(getContext(), ResourceTable.String_iamutkarshtiwari_github_io_ananas_save_error);
                });

        compositeDisposable.add(saveStickerDisposable);
    }

    /**
     * 使用矩阵修改原图
     *
     * @param mainBitmap 原图
     * @return 修改后的新bitmap
     */
    private Single<PixelMap> applyStickerToImage(PixelMap mainBitmap) {
        return Single.fromCallable(() -> {
            Matrix touchMatrix = editImageAbility.getImageViewMatrix();

            //Bitmap.createBitmap(mainBitmap).copy(
            //    Bitmap.Config.ARGB_8888, true);
            PixelMap.InitializationOptions config = new PixelMap.InitializationOptions();
            config.pixelFormat = PixelFormat.ARGB_8888;
            config.editable = true;
            PixelMap resultBitmap = PixelMap.create(mainBitmap, config);
            Canvas canvas = new Canvas(new Texture(resultBitmap));

            float[] data = touchMatrix.getData();
            Matrix3 cal = new Matrix3(data);
            Matrix3 inverseMatrix = cal.inverseMatrix();
            Matrix matrix = new Matrix(inverseMatrix.getValues());
            handleImage(canvas, matrix);
            return resultBitmap;
        });
    }

    /**
     * 对原图进行修改
     *
     * @param canvas 画布
     * @param m      修改后的矩阵
     */
    private void handleImage(Canvas canvas, Matrix m) {
        LinkedHashMap<Integer, StickerItem> addItems = stickerView.getBank();
        for (Integer id : addItems.keySet()) {
            StickerItem item = addItems.get(id);
            item.matrix.postConcat(m);
            canvas.setMatrix(item.matrix);
            canvas.drawPixelMapHolder(new PixelMapHolder(item.bitmap), 0, 0, new Paint());
        }
    }
}
